package com.ams.io.network.connection;

import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;

import com.ams.io.network.Dispatcher;

public abstract class NetworkConnector extends Connection {
    private static Dispatcher dispatcher = null;
    protected long keepAliveTime;

    public abstract boolean finishConnect() throws IOException;

    public abstract void readChannel() throws IOException;

    public abstract void writeToChannel(ByteBuffer[] data) throws IOException;

    public abstract SelectableChannel getChannel();

    public abstract SocketAddress getLocalEndpoint();

    public abstract SocketAddress getRemoteEndpoint();

    public void keepAlive() {
        keepAliveTime = System.currentTimeMillis();
    }

    public long getKeepAliveTime() {
        return keepAliveTime;
    }

    public synchronized void flush() throws IOException {
        if (outStream != null) {
            outStream.flush();
        }
        ByteBuffer[] buf = pollOutBuffers();
        if (buf.length > 0) {
            writeToChannel(buf);
        }
    }

    public void close(boolean keepAlive) {
        close();
        try {
            if (!keepAlive) {
                Channel channel = getChannel();
                if (channel != null)
                    channel.close();
            }
        } catch (IOException e) {
        }
    }

    protected static synchronized Dispatcher getDispatcher() throws IOException {
        if (dispatcher == null) {
            dispatcher = new Dispatcher();
            Thread t = new Thread(dispatcher, "connector dispatcher");
            t.setDaemon(true);
            t.start();
        }
        return dispatcher;
    }

}
